#include "favorite.h"
#include "bbs.h"

// Refer to the code of Board and Topic, they use a public QHttp to connect.
// So, they will actually refresh one by one
// When timer = 0, just disconnect all slots
void Favorite::setTimer(QTimer * timer){
    foreach (Board * board, boards)
	disconnect(board, SLOT(refreshMe()));
    foreach (Topic * topic, topics)
	disconnect(topic, SLOT(refreshMe()));
    if (timer == 0) return;
    foreach (Board * board, boards)
	connect(timer, SIGNAL(timeout()), board, SLOT(refreshMe()));
    foreach (Topic * topic, topics)
	connect(timer, SIGNAL(timeout()), topic, SLOT(refreshMe()));
}

bool Favorite::checkFavorite(Article * article){
    QString key;
	
    key = article->author->getProperty("id");
    if (userIds.contains(key)){
	alarm(article);
	emit newFavorite(501, tr("Author '%1' post a new article.").arg(key), article);
	return true;
    }
    
    key = article->topic;
    if (topicNames.contains(key)){
	alarm(topics.value(topicNames.indexOf(key)));
	emit newFavorite(502, tr("Topic '%1' get a new article.").arg(key), article);
	return true;
    }

    key = article->board;
    if (boardNames.contains(key)){
	alarm(boards.value(boardNames.indexOf(key)));
	emit newFavorite(503, tr("Board '%1' get a new article.").arg(key), article);
	return true;
    }
    return false;
}

QVector<Board *> * Favorite::getFavoriteBoard() {
    return &boards;
}

QVector<Topic *> * Favorite::getFavoriteTopic() {
    return &topics;
}

// Return false when we already mark this board as favorite
bool Favorite::addFavoriteBoard(Board * board){
    //DEBUG_F();
    QString name = board->name;
    if (boardNames.contains(name))
	return false;
    boardNames << name;
    boards << board;
    return true;
}

// Return false when we already mark this topic as favorite
bool Favorite::addFavoriteTopic(Topic * topic){
    DEBUG_F();
    QString name = topic->name;
    if (topicNames.contains(name))
	return false;
    topicNames << name;
    topics << topic;
    return true;
}
// Return false when we already mark this user id as favorite
bool Favorite::addFavoriteUser(QString userId){
    DEBUG_F();
    if (userIds.contains(userId))
	return false;
    userIds << userId;
    return true;
}
